package com.joseph.websocket.test;

import com.alibaba.fastjson.JSON;
import com.joseph.websocket.bean.Message;
import com.joseph.websocket.util.CmdEnum;
import org.apache.commons.lang3.StringUtils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.concurrent.TimeUnit;

public class MyWsClient extends WebSocketClient {

    private Map<String, Message> dataBuffer = new HashMap<>();

    private Timer timer = new Timer();

    private long lastHeartTime;

    public MyWsClient(URI serverUri) {
        super(serverUri);
    }

    public void init() {
        setConnectionLostTimeout(0);
        try {
            connectBlocking(3, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        timer.purge()
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        System.out.println("connected!");
    }

    @Override
    public void onMessage(String s) {
        if (StringUtils.isEmpty(s)) {
            return;
        }
        Message message = JSON.parseObject(s, Message.class);
        if (message.getCmd() == CmdEnum.ACK.getCode()) {
            dataBuffer.remove(message.getSeqId());
        } else if (message.getCmd() == CmdEnum.HEART.getCode()) {
            lastHeartTime = message.getMsgTime();
            System.out.println("recv heart resp");
        }
        System.out.println("recv msg from serer :" + s);
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("closed!");
    }

    @Override
    public void onError(Exception ex) {
        System.out.println("error!");
    }

}
